package utgame.com.basedemo;

import android.os.Environment;
import android.util.Log;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import static android.os.Environment.DIRECTORY_DOWNLOADS;

/**
 * Created by xueal on 2018/1/26.
 */

public class Utils {

    private static final String FILE_PATH = Environment.getExternalStoragePublicDirectory(DIRECTORY_DOWNLOADS) + "/xan/";
    private static final String FILE_NAME = "xan.txt";

    public static void writeFile(String tag, String content){
        try {
            //获取手机本身存储根目录Environment.getExternalStoragePublicDirectory("")
            //sd卡根目录Environment.getExternalStorageDirectory()
//            String path = Environment.getExternalStoragePublicDirectory("") + "/111myprint/";
//            String fileName = "print.txt";
            File file = new File(FILE_PATH);
            if (!file.exists()) {
                if (!file.mkdirs()){
                    Log.e("Utils", "mkdir failed");
                }
            }
            //第三个参数：真，后续内容被追加到文件末尾处，反之则替换掉文件全部内容
            FileWriter fw = new FileWriter(FILE_PATH + FILE_NAME, true);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write("[" + tag + "] " + getCurrentTime());
            bw.write(content + System.getProperty("line.separator"));
//            bw.append("在已有的基础上添加字符串");
//            bw.write("abc\r\n ");// 往已有的文件上添加字符串
//            bw.write("def\r\n ");
//            bw.write("hijk ");
//            bw.write("hijk ");
//            bw.write("hijk ");
            bw.close();
            fw.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String getCurrentTime(){
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date_today = simpleDateFormat.format(date);
        return date_today + "\n";
    }

    public static String StringJoin(String sep, String[] strList){
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < strList.length; ++i){
            stringBuilder.append(strList[i]);
            if (i == (strList.length - 1)) break;
            stringBuilder.append(sep);
        }
        return stringBuilder.toString();
    }
}
